package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import business.LaCorunaDelegator;
import dto.ArticuloDTO;
import dto.OfertaDTO;

/**
 * Servlet implementation class for Servlet: OFADGenerador
 *
 */
 public class OFADGenerador extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   private static final String LISTADO_TENTATIVO = "/WEB-INF/jsp/listado_tentativo.jsp";   
   private static final String OFAD_PAGE = "/WEB-INF/jsp/listado_ofads.jsp";
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public OFADGenerador() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			LaCorunaDelegator delegator = LaCorunaDelegator.getInstance();
			List<String> refs_seleccionados= getRefs(request);
			delegator.generarOFAD(refs_seleccionados);
			List<OfertaDTO> ofads= delegator.getListdoOFAD();
			request.setAttribute("ofads", ofads);
			String mensaje= "Ofad creada correctamente";
			request.setAttribute("mensaje", mensaje);
			getServletContext().getRequestDispatcher(OFAD_PAGE).forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
	}  	
	
	private List<String> getRefs(HttpServletRequest request) {
		String count = request.getParameter("checkbox-count");
		int i;
		try{
			i= Integer.parseInt(count);
		}catch (Exception e) {
			i = 0;
		}
		List<String> result = new ArrayList<String>();
		System.out.println("Getting ids...");
		int j= 1;
		String a = request.getParameter(Integer.toString(j));
		while(j <= i){
			System.out.println("El id encontrado es " + a);
			if(a!=null){
				result.add(a);
			}
			j++;
			a = request.getParameter(Integer.toString(j));
		}
		return result;
	}

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}   	  	    
}